#![allow(non_snake_case)]
use leptos::prelude::*;
use shq_web_controls::MultiTreeSelect;

// 导入服务器函数
use crate::utils::server_functions::{get_role, get_user_roles};

#[component]
pub fn UserRoleComponent(    
    sel_user_id: ReadSignal<Option<u32>>,
    selected_role_ids: RwSignal<Vec<String>>,
) -> impl IntoView {
    // 获取角色数据
    let role_items = Resource::new(
        move || (),
        |_| async { get_role().await }
    );
    
    // 获取用户已分配的角色
    let user_roles = Resource::new(
        move || sel_user_id.get(),
        |user_id_opt| async move {
            if let Some(user_id) = user_id_opt {
                get_user_roles(user_id).await
            } else {
                Ok(Vec::new())
            }
        }
    );
    let sel_menu_ids = Memo::new(move |_| {
        let sel_menu_ids: Vec<String> = user_roles.get()
            .iter()
            .flat_map(|menu_id_result| match menu_id_result {
                Ok(menu_ids) => menu_ids.iter()
                    .map(|id| {
                        // 处理转义引号，移除多余的引号
                        let s = format!("{:?}", id);
                        s.trim_matches('"').to_string()
                    })
                    .collect::<Vec<String>>(),
                Err(_) => vec![],
            })
            .collect();
        sel_menu_ids
    });
    let on_change = move |values: Vec<String>| {
        selected_role_ids.set(values);
    };
    view! {
        <div class="bg-white shadow rounded-lg p-4 flex-1 flex flex-col min-h-1">
            <h1 class="text-xl font-bold mb-4">角色</h1>
            <Suspense fallback=|| view! { <progress class="progress w-56"></progress> }>
                {move || match role_items.get() {
                    Some(Ok(roles)) => {
                        let tree_items = StoredValue::new(roles.into());
                        view! {
                            <div class="flex-1 overflow-y-auto min-h-1">
                                <MultiTreeSelect
                                    tree_items
                                    show_confirm_cancel_btn=false
                                    on_change
                                    values = sel_menu_ids.get()
                                />
                            </div>
                        }.into_any()
                    }
                    Some(Err(e)) => {
                        view! {
                            <div class="p-4 text-red-500">
                                {e.to_string()}
                            </div>
                        }.into_any()
                    }
                    None => {
                        view! {
                            <div class="flex-1 flex items-center justify-center">
                                "正在加载菜单数据..."
                            </div>
                        }.into_any()
                    }
                }}
            </Suspense>
        </div>
    }
    .into_any()
}
